package cn.mesmile.groovy.core;

import cn.mesmile.groovy.cache.GroovyInfo;
import cn.mesmile.groovy.cache.GroovyInnerCache;
import org.springframework.scripting.ScriptSource;
import org.springframework.util.StringUtils;

import java.io.IOException;

/**
 * @author zb
 * @date 2021/11/25 15:44
 * @Description
 */
public class DatabaseScriptSource implements ScriptSource {

	/**
	 * 脚本名称
	 */
	private String scriptName;

	/**
	 * 构造函数
	 *
	 * @param scriptName
	 */
	public DatabaseScriptSource(String scriptName) {
		this.scriptName = scriptName;
	}

	/**
	 * @see org.springframework.scripting.ScriptSource#getScriptAsString()
	 */
	@Override
	public String getScriptAsString() throws IOException {
		// 从内部缓存获取
		GroovyInfo groovyInfo = GroovyInnerCache.getByName(scriptName);
		if (groovyInfo != null) {
			return groovyInfo.getGroovyContent();
		} else {
			return "";
		}
	}

	/**
	 * @see org.springframework.scripting.ScriptSource#isModified()
	 */
	@Override
	public boolean isModified() {
		return false;
	}

	/**
	 * @see org.springframework.scripting.ScriptSource#suggestedClassName()
	 */
	@Override
	public String suggestedClassName() {
		return StringUtils.stripFilenameExtension(this.scriptName);
	}

}
